﻿using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using MaxStoreErp.Core.BaseClasses;
using MaxStoreErp.Core.Events;
using MaxStoreErp.Core.Infrastructure;
using MaxStoreErp.Core.Interfaces;
using MaxStoreErp.Core.Threading;
using Microsoft.Practices.Prism.Events;
using Microsoft.Practices.Prism.Modularity;
using Microsoft.Practices.Prism.UnityExtensions;
using Microsoft.Practices.ServiceLocation;
using Microsoft.Practices.Unity;

namespace MaxStoreErp.Shell.MetroShell
{
    class MetroShellPresenter : PresenterBase<MetroShellView, MetroShellViewModel>, IShellWindow
    {
        Task<IProgressDialogController> _progressTask;
        const string LoadingModuleText = "Загружается модуль: {0}";

        public MetroShellPresenter() : base("MaxStore ERP")
        {
            ServiceLocator.Current.GetInstance<IEventAggregator>().GetEvent<ModuleLoadedEvent>().Subscribe(ModuleLoaded);
            ServiceLocator.Current.GetInstance<IEventAggregator>().GetEvent<ModuleLoadingEvent>().Subscribe(OnLoadingModule);
            ServiceLocator.Current.GetInstance<IEventAggregator>().GetEvent<ChangedUserEvent>().Subscribe(OnUserChanged);
        }

        void OnUserChanged(IUser user)
        {
            ViewModel.CurrentUser = user;
            UnlockToolbar();
        }

        async void OnLoadingModule(ModuleLoadingEventArgs module)
        {
            var result = await _progressTask;
            result.SetMessage(string.Format(LoadingModuleText, module.ModuleName));
        }

        protected override void OnViewSet()
        {
            base.OnViewSet();
            View.Loaded += ViewOnLoaded;
        }

        void ViewOnLoaded(object sender, RoutedEventArgs routedEventArgs)
        {
            _progressTask = 
                Container.Resolve<IProgressDialog>()
                    .ShowProgressAsync("Подождите, идет загрузка модулей", "Загрузка модулей", false);
        }

        public void LockToolBar()
        {
            ViewModel.IsToolbarEnabled = false;
        }

        public void UnlockToolbar()
        {
            ViewModel.IsToolbarEnabled = true;
        }

        public string WindowTitle
        {
            get
            {
                return ViewModel.Header;
            }
            set
            {
                ViewModel.Header = value;
            }
        }

        public IView ShellView
        {
            get
            {
                return View;
            }
        }

        public void PlaceToolBarItems(IList<FrameworkElement> items)
        {
            foreach (var item in items)
            {
                var dataContext = item.DataContext;
                DetachItem(item);
                item.DataContext = dataContext;
                View.MainToolBar.Items.Add(item);
            }
        }

        public void RemoveToolBarItems(IList<FrameworkElement> items)
        {
            foreach (var item in items)
            {
                View.MainToolBar.Items.Remove(item);
            }
        }

        public void PlaceStatusBarItems(IList<FrameworkElement> items)
        {
            foreach (var item in items)
            {
                DetachItem(item);
                View.MainStatusBar.Items.Add(item);
            }
        }

        public void RemoveStatusBarItems(IList<FrameworkElement> items)
        {
            foreach (var item in items)
            {
                View.MainStatusBar.Items.Remove(item);
            }
        }

        void DetachItem(FrameworkElement element)
        {
            if (element.Parent == null)
                return;

            var parent = element.Parent as ItemsControl;
            if (parent == null)
                return;

            parent.Items.Remove(element);
        }

        async void ModuleLoaded(IEnumerable<ModuleInfo> moduleInfos)
        {
            var controller = await _progressTask;
            await controller.CloseAsync();
            var docManager = Container.Resolve<IDocumentManager>();
            ThreadHelper.SafeCall(() =>
            {
                var userLogin = Container.TryResolve<IUserLogin>();
                if (userLogin == null)
                {
                    docManager.NavigateToMenu();
                    return;
                }

                docManager.NavigateToLogin();
            });
        }

        protected override void OnDataLoading()
        {
            base.OnDataLoading();
            var commands = Container.Resolve<ShellGlobalCommands>();
            ViewModel.LoginUserCommand = commands.Login;
            ViewModel.ShowNavigationWindowCommand = commands.MainMenu;
            ViewModel.Back = commands.Back;
        }
    }
}
